<?php
# 这里的是token的黑名单的操作，为了增加用户的安全性
namespace App\Models;

use App\Config\Database;
use PDO;
use PDOException;
class TokenBlacklist{ 
    private $conn;
    private $table = 'TokenBlacklist';

    public function __construct() {
        //数据库的初始化
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    /**
     * 将Token加入黑名单
     * @param string $jti Token唯一标识
     * @param int $userId 用户ID
     * @param int $expiresAt 过期时间戳
     * @return bool
     */
    public function addToBlacklist($jti, $userId, $expireAt) {
        try {
            $query = "INSERT INTO " . $this->table . " (jti, user_id, expire_at) VALUES (:jti, :user_id, :expire_at)";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':jti', $jti);
            $stmt->bindParam(':user_id', $userId);
            $stmt->bindParam(':expire_at', $expireAt);
            return $stmt->execute();
        } catch(PDOException $e) {
            error_log("Add to blacklist error: " .$e->getMessage());
            return false;
        }
    }

    /**
     * 检查Token是否在黑名单中
     * @param string $jti Token唯一标识
     * @return bool
     */
    public function isInBlacklist($jti) {
        try {
            $query = "SELECT * FROM " . $this->table . " WHERE jti = :jti LIMIT 1";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':jti', $jti);
            $stmt->execute();
            return $stmt->rowCount() > 0;
        } catch(PDOException $e) {
            error_log("Check blacklist error: " .$e->getMessage());
            return false;
        }
    }

    /**
     * 清理过期的黑名单记录
     * @return bool
     */
    public function cleanExpiredTokens() {
        try {
            $currentTime = time();
            $query = "DELETE FROM " . $this->table . " WHERE expires_at < :current_time";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':current_time', $currentTime);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Clean expired tokens error: " . $e->getMessage());
            return false;
        }
    }
}
?>